<?php
/**
 * API交互类
 *
 * @package DeepSeekAISummarizer
 * @since 3.7.2
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 防止重复声明类
if (!class_exists('DeepSeekAI_API')) {

class DeepSeekAI_API {
    
    private $plugin;
    private $provider;
    private $api_key;
    private $model;
    private $max_tokens;
    private $temperature;
    private $api_url;
    
    /**
     * 构造函数，初始化API配置
     */
    public function __construct($plugin) {
        $this->plugin = $plugin;

        // 新的、统一的配置读取方式
        $this->provider = get_option('deepseek_ai_provider', 'zhipu');
        $provider_configs = get_option('deepseek_ai_provider_configs', array());

        $current_provider_config = isset($provider_configs[$this->provider]) ? $provider_configs[$this->provider] : array();
        
        $models_config = DeepSeekAI_Models_Config::get_instance();
        $provider_defaults = $models_config->get_provider($this->provider);

        // 设置API Key
        $this->api_key = !empty($current_provider_config['api_key']) ? $current_provider_config['api_key'] : '';

        // 设置模型
        if (!empty($current_provider_config['model'])) {
            $this->model = $current_provider_config['model'];
        } else if ($provider_defaults && !empty($provider_defaults['models'][0]['id'])) {
            $this->model = $provider_defaults['models'][0]['id'];
        } else {
            $this->model = ''; // Fallback
        }

        // 设置最大Token数
        if (!empty($current_provider_config['max_tokens'])) {
            $this->max_tokens = $current_provider_config['max_tokens'];
        } else if ($provider_defaults && isset($provider_defaults['parameters']['max_tokens']['default'])) {
            $this->max_tokens = $provider_defaults['parameters']['max_tokens']['default'];
        } else {
            $this->max_tokens = 500; // Fallback
        }
        
        // 设置温度
        if (isset($current_provider_config['temperature'])) {
            $this->temperature = $current_provider_config['temperature'];
        } else if ($provider_defaults && isset($provider_defaults['parameters']['temperature']['default'])) {
            $this->temperature = $provider_defaults['parameters']['temperature']['default'];
        } else {
            $this->temperature = 0.7; // Fallback
        }
        
        // 设置API URL
        if ($provider_defaults && !empty($provider_defaults['api_url'])) {
            $this->api_url = $provider_defaults['api_url'];
        } else {
            $this->api_url = ''; // Fallback
        }
    }
    
    /**
     * 生成摘要
     * @param string $content
     * @return string
     */
    public function generate_summary($content) {
        $prompt = '请为以下内容生成一段80-150字的中文摘要，要求如下：1. 不要出现"本文/这篇文章"等词语。2. 风格正式、客观。3. 重点突出，逻辑清晰。\n\n内容如下：\n' . $content;
        
        $messages = array(
            array('role' => 'user', 'content' => $prompt)
        );
        
        $data = $this->call($messages);
        
        if (isset($data['choices'][0]['message']['content'])) {
            $summary = trim($data['choices'][0]['message']['content']);
            $this->plugin->info_log('API成功返回摘要内容');
            return $summary;
        } else {
            $this->plugin->error_log('API返回数据格式不正确，无法获取摘要', $data);
            return '';
        }
    }
    
    /**
     * 生成SEO内容
     * @param string $title
     * @param string $content
     * @return array
     */
    public function generate_seo_content($title, $content) {
        $prompt = '你是一位专业的SEO专家，请为以下文章生成SEO相关内容，并以JSON格式返回。JSON应包含三个键：seo_title (string, 80字符以内), seo_description (string, 150字符以内), seo_keywords (string, 逗号分隔的3-5个核心关键词)。\n\n文章标题：' . $title . '\n文章内容：\n' . $content;
        
        $messages = array(
            array('role' => 'user', 'content' => $prompt)
        );
        
        $data = $this->call($messages);
        
        if (isset($data['choices'][0]['message']['content'])) {
            $raw_content = $data['choices'][0]['message']['content'];
            // 尝试从代码块中提取JSON
            preg_match('/```json\s*([\s\S]+?)\s*```/', $raw_content, $matches);
            $json_string = isset($matches[1]) ? trim($matches[1]) : $raw_content;
            
            $seo_data = json_decode($json_string, true);
            
            if (json_last_error() === JSON_ERROR_NONE && is_array($seo_data) && isset($seo_data['seo_title'])) {
                $this->plugin->info_log('API成功返回并解析了SEO内容');
                return $seo_data;
            } else {
                $this->plugin->error_log('无法解析API返回的SEO JSON数据', $raw_content);
                return array();
            }
        } else {
            $this->plugin->error_log('API返回数据格式不正确，无法获取SEO内容', $data);
            return array();
        }
    }

    /**
     * 生成引导内容
     * @param string $prompt
     * @return string
     */
    public function generate_guide_content($prompt) {
        $messages = array(
            array('role' => 'user', 'content' => $prompt)
        );

        $data = $this->call($messages);

        if (isset($data['choices'][0]['message']['content'])) {
            $guide = trim($data['choices'][0]['message']['content']);
            // 移除可能的代码块标记
            $guide = preg_replace('/^```html\s*|```$/', '', $guide);
            $this->plugin->info_log('API成功返回引导内容');
            return $guide;
        } else {
            $this->plugin->error_log('API返回数据格式不正确，无法获取引导内容', $data);
            return '';
        }
    }

    /**
     * 通用API调用方法
     * @param array $messages
     * @param array $tools
     * @return array|null
     */
    private function call($messages, $tools = array()) {
        $this->plugin->info_log('开始调用API，类型 = ' . (empty($tools) ? 'summary/seo/guide' : 'tools'));
        
        if (empty($this->api_key)) {
            $provider_name = '未知服务商';
            $models_config = DeepSeekAI_Models_Config::get_instance();
            $provider_info = $models_config->get_provider($this->provider);
            if ($provider_info && isset($provider_info['name'])) {
                $provider_name = $provider_info['name'];
            }
            $this->plugin->error_log($provider_name . ' API Key未配置');
            return null;
        }

        $body = array(
            'model' => $this->model,
            'messages' => $messages,
            'max_tokens' => $this->max_tokens,
            'temperature' => $this->temperature,
            'stream' => false,
        );

        // 特定于提供商的调整
        if ($this->provider === 'zhipu') {
            unset($body['stream']); // 智谱v4不支持stream参数，除非是SSE
            if (!empty($tools)) {
                $body['tools'] = $tools;
            }
        }
        
        $this->plugin->debug_log('API 请求 Body: ', $body);
        
        $headers = $this->get_request_headers();
        
        $response = wp_remote_post($this->api_url, array(
            'method' => 'POST',
            'headers' => $headers,
            'body' => json_encode($body),
            'timeout' => 120
        ));
        
        if (is_wp_error($response)) {
            $this->plugin->error_log('API 请求失败: ' . $response->get_error_message());
            return null;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        
        $this->plugin->debug_log('API 响应代码: ' . $response_code);
        $this->plugin->debug_log('API 响应 Body: ', json_decode($response_body, true));
        
        if ($response_code >= 200 && $response_code < 300) {
            $data = json_decode($response_body, true);
            if (isset($data['error'])) {
                $error_message = isset($data['error']['message']) ? $data['error']['message'] : '未知API错误';
                $this->plugin->error_log('API返回错误: ' . $error_message);
                return null;
            }
            return $data;
        } else {
            $this->plugin->error_log('API 请求返回非2xx状态码: ' . $response_code);
            $this->plugin->error_log('API 错误响应: ' . $response_body);
            return null;
        }
    }
    
    /**
     * 获取API请求头
     * @return array
     */
    private function get_request_headers() {
        switch ($this->provider) {
            case 'zhipu':
                return array(
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $this->generate_zhipu_token($this->api_key)
                );
            case 'deepseek':
            case 'volcengine':
                return array(
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $this->api_key
                );
        }
        return array('Content-Type' => 'application/json');
    }

    /**
     * 生成智谱清言的JWT Token
     * @param string $api_key
     * @return string
     */
    private function generate_zhipu_token($api_key) {
        $parts = explode('.', $api_key);
        if (count($parts) !== 2) {
            $this->plugin->error_log('智谱清言 API Key 格式不正确');
            return '';
        }
        $id = $parts[0];
        $secret = $parts[1];
        
        $header = array('alg' => 'HS256', 'sign_type' => 'SIGN');
        $payload = array(
            'api_key' => $id,
            'exp' => time() + 3600, // token有效期1小时
            'timestamp' => time() * 1000 // 毫秒级时间戳
        );

        $base64_header = $this->base64_url_encode(json_encode($header, JSON_UNESCAPED_UNICODE));
        $base64_payload = $this->base64_url_encode(json_encode($payload, JSON_UNESCAPED_UNICODE));
        
        $signature = hash_hmac('sha256', $base64_header . '.' . $base64_payload, $secret, true);
        $base64_signature = $this->base64_url_encode($signature);

        return $base64_header . '.' . $base64_payload . '.' . $base64_signature;
    }

    /**
     * Base64 URL安全编码
     * @param string $data
     * @return string
     */
    private function base64_url_encode($data) {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }
}

}